package ioc

import (
	"fmt"
	"reflect"
)

// 全局函数调用,存储所有的全局函数
var funcMapAll = make(map[string]interface{})

// 注册全局函数
func RegisterFuncAll(funcName string, f interface{}) {
	//判断是否已经存在
	if _, ok := funcMapAll[funcName]; ok {
		panic("全局函数已经注册过了")
	}
	funcMapAll[funcName] = f
}

// 执行全局函数
func ExecuteFunc(funcName string, args ...interface{}) interface{} {
	if callBack, ok := funcMapAll[funcName]; ok {
		in := make([]reflect.Value, len(args))
		for i, arg := range args {
			in[i] = reflect.ValueOf(arg)
		}
		outList := reflect.ValueOf(callBack).Call(in)
		result := make([]interface{}, len(outList))
		for i, out := range outList {
			result[i] = out.Interface()
		}
		//如果长度为1,则直接返回
		if len(result) == 1 {
			return result[0]
		}
		return result
	} else {
		var args1 = ""
		for _, v := range args {
			args1 += fmt.Sprintf("%v,", v)
		}
		//去掉最后一个逗号
		args1 = args1[:len(args1)-1]
		panic(fmt.Errorf("%s(%s) not found", funcName, args1))
	}
}
